package priv.dajie.tzzq.common;

public class Retryer {
    private int times = 3;
    private int max = 3;
    private Retryable retryable;

    public Retryer(Retryable retryable) {
        this.retryable = retryable;
    }

    public Retryer setTimes(int times) {
        this.times = times;
        return this;
    }

    public void start() throws RuntimeException {
        while (true) {
            try {
                retryable.run();
                break;
            }catch (Exception e){
                try {
                    Thread.sleep(3000 * (max-times+1));
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                if(--times == 0)
                    throw new RuntimeException(e);
            }
        }
    }

    public static void retry(Retryable retryable) throws RuntimeException {
        new Retryer(retryable).start();
    }

    public static void retry(Retryable retryable, int times) throws RuntimeException {
        new Retryer(retryable).setTimes(times).start();
    }

}
